﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using mdryden.Core.Security;
using mdryden.Core.Settings;

namespace LastoRevival.Website.Settings
{
	public class WebsiteSettings
	{

		static WebsiteSettings instance;
		static object singletonLock = new object();


		public string DefaultTheme { get; private set; }
		public string ConnectionString { get; private set; }
		public string BreadCrumbSeperator { get; private set; }
		public int ThreadsPerPage { get; private set; }
		public string[] RegisteredThemes { get; private set; }
		public int DefaultCollapseThreshold { get; private set; }


		public static WebsiteSettings GetInstance()
		{
			if (instance == null)
			{
				lock (singletonLock)
				{
					if (instance == null)
					{
						instance = CreateInstance();
					}
				}
			}

			return instance;
		}


		private static WebsiteSettings CreateInstance()
		{
			var newInstance = new WebsiteSettings
			{
				DefaultTheme = SettingsHelper.LoadRequiredAppSetting("DefaultTheme"),
				ConnectionString = GetConnectionString(),
				BreadCrumbSeperator = SettingsHelper.LoadRequiredAppSetting("BreadCrumbSeperator"),
				ThreadsPerPage = int.Parse(SettingsHelper.LoadRequiredAppSetting("ThreadsPerPage")),
				RegisteredThemes = GetRegisteredThemes("RegisteredThemes"),
				DefaultCollapseThreshold = int.Parse(SettingsHelper.LoadRequiredAppSetting("DefaultCollapseThreshold")),
			};

			return newInstance;
		}

		private static string GetConnectionString()
		{
			var key = SettingsHelper.LoadRequiredAppSetting("ActiveConnection");
			var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;

			return connectionString;
		}
		
		private static string[] GetRegisteredThemes(string key)
		{
			var themes = SettingsHelper.LoadRequiredAppSetting(key);

			var split = themes.Split(',');

			var strings = new List<string>();

			foreach (var theme in split)
			{
				strings.Add(theme.Trim());
			}

			return strings.ToArray();
		}

	}
}
